package ace.cmp.rest.spring.data.jdbc.querydsl.test.core.service;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.dao.entity.Author;
import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.dao.entity.Book;
import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.dao.repository.AuthorRepository;
import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.dao.repository.BookRepository;
import java.util.Arrays;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author caspar
 * @date 2023/8/26 17:01
 */
@Component
@AllArgsConstructor
@Slf4j
public class InitDataService {
  private final AuthorRepository authorRepository;
  private final BookRepository bookRepository;

  @Transactional(rollbackFor = Exception.class)
  public void init() {
    List<Author> authors =
        Arrays.asList(this.createAuthor(1L), this.createAuthor(2L), this.createAuthor(3L));
    List<Book> books =
        Arrays.asList(
            this.createBook(1L, 1L),
            this.createBook(2L, 1L),
            this.createBook(3L, 2L),
            this.createBook(4L, 3L),
            this.createBook(5L, 0L));
    authorRepository.insert(authors);
    bookRepository.insert(books);
  }

  private Author createAuthor(Long id) {
    return Author.builder()
        .id(id)
        .title(id.toString())
        .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
        .createTime(System.currentTimeMillis())
        .updateTime(System.currentTimeMillis())
        .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
        .build();
  }

  private Book createBook(Long id, Long authorId) {
    return Book.builder()
        .id(id)
        .title(id.toString())
        .title2(id.toString())
        .pages(authorId)
        .authorId(authorId)
        .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
        .createTime(System.currentTimeMillis())
        .updateTime(System.currentTimeMillis())
        .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
        .build();
  }
}
